<?php

namespace Home\Controller;

use Think\Controller;

include_once("Common.php");
include_once("mysqlha.php");
header("Content-Type:text/html; charset=utf-8");

class WithdrawController extends CommonController
{
    //绑定支付宝
    public function bangZ()
    {
        $userid = $_GET['userid'];
        $zhifuname = $_GET['zhifuname'];
        $zhifucount = $_GET['zhifucount'];

        $realname = M('user_certification')->where(['types' => 1, 'user_id' => $userid])->getField('data2');
        if($realname){
            if ($realname != $zhifuname) {
                exit(json_encode(['code' => 201, 'msg' => '提现账户姓名需与实名信息姓名一致'], JSON_UNESCAPED_UNICODE));
            }
        }

        $updateArr = array(
            "zhifuname" => $zhifuname,
            "zhifucount" => $zhifucount
        );
        update('user', $updateArr, "id=" . $userid . "");
        $returnarr = array(
            "code" => 200,
            "msg" => "设置成功"
        );

        $this->CheckWarn($userid, '绑定支付宝');
        echo json_encode($returnarr, JSON_UNESCAPED_UNICODE);
    }

    //提现
    public function tiXian()
    {
        //exit(json_encode(['code' => 201, 'msg' => '请先下载安装最新版本']));

        $hour = date('H');
        $minute = date('i');

        /*if ($hour >= 17) {
            exit(json_encode(['code' => 201, 'msg' => '提现时间00:00 - 17:00']));
        }*/

        // if ($hour < 16) {
        //     exit(json_encode(['code' => 201, 'msg' => '提现时间16:00 - 23:59']));
        // }
        // if ($hour < 16 || ($hour == 16 && $minute < 50)) {
        //     exit(json_encode(['code' => 201, 'msg' => '提现时间16:50 - 23:59']));
        // }

        $config_withdrawtime = M('config_system')->where(['category' => 'withdrawtime'])->getField('title, content');

        if (intval($config_withdrawtime['withdraw_minute']) == 0 && $hour < $config_withdrawtime['withdraw_hour']) {
            exit(json_encode(['code' => 201, 'msg' => '提现时间'.$config_withdrawtime['withdraw_hour'].':00 - 23:59']));
        }

        if ($hour < $config_withdrawtime['withdraw_hour'] || ($hour == $config_withdrawtime['withdraw_hour'] && $minute < intval($config_withdrawtime['withdraw_minute']))) {
            exit(json_encode(['code' => 201, 'msg' => '提现时间'.$config_withdrawtime['withdraw_hour'].':'.$config_withdrawtime['withdraw_minute'].' - 23:59']));
        }

        $id = I('id');
        $id = intval($id);
        $userid = $_REQUEST['userid'];
        $paymethod = $_REQUEST['method'];

        $style = M('withdraw_style')->where(['id' => $id])->find();
        if (!$style) {
            exit(json_encode(['code' => 201, 'msg' => '选择有误']));
        }


        $config = M('config_system')->where(['title' => 'rate'])->getField('title, content');
        if($style['money'] * $config['rate'] < $style['price']){
            exit(json_encode(['code' => 201, 'msg' => '提现异常']));
        }




        $today_start = strtotime(date('Y-m-d'));
        
        $withdrawoftoday = M('withdraw')->where(['userid'=>$userid, 'create_time'=>array('egt',$today_start)])->find();
        if($withdrawoftoday && $withdrawoftoday['paymethod'] != $paymethod){
            exit(json_encode(['code' => 400, 'msg' => '提现方式必须与今日首次提现方式一致']));
        }


        $paymethodstext = ['微信', '支付宝'];
        $paymethodslimit = [120000, 99999999];
        $withdrawoftodaycount = M('withdraw')->where(['paymethod'=>$paymethod, 'create_time'=>array('egt',$today_start)])->sum('money');
        if($withdrawoftodaycount >= $paymethodslimit[$paymethod]){
            exit(json_encode(['code' => 400, 'msg' => $paymethodstext[$paymethod] . '当天提现已满，可选择' . $paymethodstext[$paymethod == 0 ? 1 : 0]]));
        }
        usleep(500000);

        $config = M('config_system')->where(['category' => 'withdraw'])->getField('title, content');

        $shouxu_rate = $config['shouxu'];

        $shouxu = $shouxu_rate * $style['price'];

        $user = M('user')->master(true)->where(['id' => $userid])->find();


        if($user['realname_auth']!=2){
            exit(json_encode(['code' => 400, 'msg' => '请先实名认证，再进行提现操作']));
        }
        $tixianlimit = M('withdraw_limit')->find($user['id']);
        if($tixianlimit){
            exit(json_encode(['code' => 400, 'msg' => '提现已被拒绝']));
        }

        $frozen = M('wallet_frozen')->where(['user_id'=>$userid])->find();
        if($frozen){
            $user['score'] = $user['score'] - $frozen['value'];
        }

        if ($user['score'] < ($style['price'] + $shouxu)) {
            $msg = '账户余额不足';

            if ($shouxu > 0) {
                $msg .= ' (包含手续费：'.$shouxu.')';
            }
            exit(json_encode(['code' => 201, 'msg' => $msg]));
        }

        /*if (($user['score'] / 10) < $config['withdraw_min']) {
            $returnarr = array(
                "code" => 201,
                "msg" => "提现最低需".$config['withdraw_min']."。"
            );
            exit(json_encode($returnarr));
        }*/

        $content = '提现申请';
        if ($shouxu > 0) {
            $content .= ' (手续费：'.$shouxu.')';
        }
    
        $total = $style['price'] + $shouxu;
        $total = changefloor($total);


        $realname = M('user_certification')->where(['types' => 1, 'user_id' => $user['id']])->getField('data2');
        if($realname){
            if ($realname != $user['zhifuname']) {
                exit(json_encode(['code' => 201, 'msg' => '提现账户姓名与实名信息姓名不一致'], JSON_UNESCAPED_UNICODE));
            }
        }



        $result = D('YaoqingRecords')->index($userid, 0, $total, $content, 1, '', 1);
        if($result){
            $time = time();
            M('withdraw')->add([
                "userid" => $userid,
                "paymethod" => $paymethod,
                "money" => $style['money'],
                'price' => $style['price'],
                'shouxu' => $shouxu,
                'data' => json_encode(['name' => $user['zhifuname'], 'account' => $user['zhifucount'], 'v'=>'3', 'ip'=>$_SERVER["REMOTE_ADDR"]], JSON_UNESCAPED_UNICODE),
                'create_time' => $time,
                'update_time' => $time,
            ]);
            $this->InsertS($userid, 'zhifucounts', $user['zhifucount']);
            $this->CheckWarn($userid, '发起提现');
            exit(json_encode(['code' => 200, 'msg' => '成功提交申请']));
        }
        exit(json_encode(['code' => 201, 'msg' => '提现失败']));

    }

    // 虚拟币兑人民币比例
    public function rate()
    {
        exit(json_encode(['code' => 200, 'data' => ['rate' => 5]]));
        /*$data = M('config_system')->where(['title' => 'rate'])->getField('content');
        exit(json_encode(['code' => 200, 'data' => ['rate' => $data]]));*/
    }

    //获取用户的提现记录
    public function getRecord()
    {
        $userid = $_GET['userid'];
        $Model = M();
        $resultlist = $Model->Query("select t.money,t.price, t.shouxu,t.addtime,t.daotime,t.state,t.reason,t.paymethod,t1.zhifuname,t1.wxname from withdraw t,user t1 where t.userid=" . $userid . " and t1.id=t.userid order by t.id desc");
        $resultlist = array($resultlist);
        echo getSuccessJson($resultlist);
    }



    private function InsertS($user_id, $key, $value)
    {
        $item = M('user_repeat_check')->where(['user_id'=>$user_id])->find();
        if(!$item){
            $item = [
                'user_id'=>$user_id,
                'device_ids'=>'',
                'zhifucounts'=>'',
                'wechat_openid'=>'',
                'qq_openid'=>'',
                'ips'=>'',
            ];
            M('user_repeat_check')->add($item);
        }
        $update = [];
        $data = $item[$key] ? explode(',', $item[$key]) : [];
        if(!in_array($value, $data)){
            array_push($data, $value);
            $data = implode(',', $data);
            $update = [$key=>$data];
        }
        if(sizeof($update)){
            M('user_repeat_check')->where(['user_id'=>$user_id])->save($update);
        }
    }



    private function CheckWarn($user_id, $value)
    {
        $warn = M('user_warn')->find($user_id);
        if($warn){
            M('user_warn_records')->add(['user_id'=>$user_id, 'desc'=>$value, 'time'=>time()]);
        }else{
            $userinfo = M('user')->find($user_id);
            $userRepeatCheck = M('user_repeat_check')->find($user_id);
            if($userinfo){
                if($userRepeatCheck['zhifucounts']){
                    $zhifucounts = explode(',', $userRepeatCheck['zhifucounts']);
                    if($userinfo['zhifucount']){
                        array_push($zhifucounts, $userinfo['zhifucount']);
                    }
                    $where['user.zhifucount'] = ['in', array_unique($zhifucounts)];
                }elseif($userinfo['zhifucount']){
                    $where['user.zhifucount'] = $userinfo['zhifucount'];
                }
                if($userinfo['phone']){
                    $where['user.zhifucount'] = $userinfo['phone'];
                }
                if($userRepeatCheck['device_ids']){
                    $device_ids = explode(',', $userRepeatCheck['device_ids']);
                    if($userinfo['device_id']){
                        array_push($device_ids, $userinfo['device_id']);
                    }
                    $where['user.device_id'] = ['in', array_unique($device_ids)];
                }elseif($userinfo['device_id']){
                    $where['user.device_id'] = $userinfo['device_id'];
                }
                $where['_logic'] = 'OR';
                $warn = M('user_warn')->join('user ON user_warn.user_id=user.id')->where($where)->find();
                if($warn){
                    M('user_warn_records')->add(['user_id'=>$user_id, 'desc'=>$value . '（来源于用户 '.$warn['id'].'）', 'time'=>time()]);
                }
            }
        }
    }
}